package com.st.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.st.order.FeignClient.FeignService;
import com.st.order.entity.Order;
import com.st.order.entity.Orderitem;
import com.st.order.service.IOrderService;
import com.st.order.service.IOrderitemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Hello
 * @since 2021-11-15
 */
@RestController
@RequestMapping("/order/order")
public class OrderController {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderitemService orderitemService;

   // @Autowired
   // private RestTemplate restTemplate;
    @Autowired
    private FeignService feignService;

    @RequestMapping(value = "/queryById",produces = "application/json;charset=utf-8")
    public Map queryById(String orderId){
        // 查询订单
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",orderId);
        Order order = orderService.getOne(wrapper);
        //查询订单明细
        QueryWrapper<Orderitem> itemWrapper = new QueryWrapper<>();
        itemWrapper.eq("order_id",orderId);
        List<Orderitem> list = orderitemService.list(itemWrapper);
        // 循环准备一个列表用来远程调用
       // StringBuilder url = new StringBuilder("http://localhost:9001/book/book/queryByIds");
        //通过名字调用
        //StringBuilder url = new StringBuilder("http://book-manager/book/book/queryByIds");
        // 拼接查询条件
//        if(list!=null && list.size()>0) {
//            url.append("?");
//            for (Orderitem item : list) {
//                url.append("isbn="+item.getIsbn()+"&");
//            }
//            url.deleteCharAt(url.length()-1);
//        }
        // 远程访问book-manager 完成图书信息加载
        //String books = restTemplate.getForObject(url.toString(), String.class);

        //通过 feign 和 ribben 远程调用 负载均衡
        String[] isbns=new String[list.size()];
        int i=0;
        for(Orderitem item:list){
            isbns[i]=item.getIsbn();
            i++;
        }
        Map books=feignService.getByIds(isbns);
        Map map = new HashMap();
        map.put("order",order);
        map.put("books",books);
        return map;
    }
}
